//
//  YXTNetworking.m
//  daxue
//
//  Created by hanjun on 16/3/22.
//  Copyright © 2016年 cn.yunxuetang. All rights reserved.
//

#import "YXTNetworking.h"
#import "YXTUserUtil.h"
#import "MJExtension.h"

#define Accept @"text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8"
#define AcceptLanguage @"en-us,en;q=0.5"
#define ContentType @"application/json"

@interface YXTNetworking(){
    @private NSString * source;
    @private NSString * sourceType;
    
    @private NSString * org_Code;
    
    @private NSString * apiBaseURL;
    @private NSString * meetingApiBaseURL;
    @private NSString * meetingPayApiBaseURL;
    @private NSString * zoomSDKDomain;
}

@end

@implementation YXTNetworking

+ (instancetype)getInstance
{
    static YXTNetworking * net = nil;
    static dispatch_once_t  predicate;
    dispatch_once(&predicate,^{
        net = [[self alloc] init];
    });
    return net;
}

- (void)configPlatform:(PlatformType)platformType apiEnvironment:(APIEnvironment)apiEnvironment orgCode:(NSString *)orgCode{
    switch (platformType) {
        case PlatformTypeLeCaiVIP:
        {
            source = @"502";//大乐才iPhone
            sourceType = @"50";//产线标识(10:乐才, 50:企大)
            org_Code = orgCode;
            if (apiEnvironment==APIEnvironmentProduction) {
                apiBaseURL = @"http://api.qida.yunxuetang.cn/v1/";
                meetingApiBaseURL = @"http://api.mall.yxt.com/";
                meetingPayApiBaseURL = @"https://pay.yxt.com/";
                zoomSDKDomain = @"huihui.zoomus.cn";
            }else{
                apiBaseURL = @"http://base.qida.yunxuetang.com.cn/";
                meetingApiBaseURL = @"http://api.yunxuetang.com.cn/mallapi/";
                meetingPayApiBaseURL = @"http://pay.yunxuetang.com.cn/";
                zoomSDKDomain = @"huihuitest.zoomus.cn";
            }
            
            break;
        }
        case PlatformTypeLeCai:
        {
            source = @"102";
            sourceType = @"10";
            break;
        }
        case PlatformTypeWebSchool:
        {
            source = @"202";
            sourceType = @"50";
            break;
        }
        case PlatformTypePaperIM:
        {
            source = @"302";
            sourceType = @"50";
            break;
        }
        default:
        {
            source = @"502";
            sourceType = @"50";
            break;
        }
    }
}

/**
 *  返回设备唯一标识
 */
- (NSString *)getDeviceIdentification
{
    NSString *uuidString = [[[UIDevice currentDevice] identifierForVendor] UUIDString];
    uuidString = [uuidString stringByReplacingOccurrencesOfString:@"-" withString:@"_"];
    return [NSString stringWithFormat:@"%@%@", source,uuidString.lowercaseString];
    
}

#pragma mark - 计算字符串长度(length)
/**
 *  计算字符串长度(去掉字符串两边空格)
 *
 *  @param sourceString 需要处理的源字符串
 *
 *  @return 处理后的长度
 */
- (NSUInteger *)stringByLength:(NSString*)string {
    return (NSUInteger *)[self stringByTrimBothSides:string].length;
}

/**
 *  去掉字符串左右两边的空格
 *
 *  @param sourceString 需要处理的源字符串
 *
 *  @return 处理后的字符串
 */
- (NSString *)stringByTrimBothSides:(NSString*)string {
    //去掉左右两边的空格
    return [string stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
}


- (void)requestWihtMethod:(RequestType)methodType
                      url:(NSString*)url
                   params:(NSDictionary*)params
                  success:(void (^)(NSURLSessionDataTask *task,id response))success
                  failure:(void (^)(NSURLSessionDataTask * task, NSError *error))failure
{
    // 状态栏显示菊花
    [UIApplication sharedApplication].networkActivityIndicatorVisible = YES;
    NSLog(@"url:%@",url);
    NSLog(@"params:%@",params);
    AFHTTPSessionManager* manager = [AFHTTPSessionManager manager];
    manager.requestSerializer = [AFJSONRequestSerializer serializer];
    manager.responseSerializer = [AFJSONResponseSerializer serializer];
    [manager.requestSerializer setValue:Accept forHTTPHeaderField:@"Accept"];
    [manager.requestSerializer setValue:AcceptLanguage forHTTPHeaderField:@"Accept-Language"];
    [manager.requestSerializer setValue:ContentType forHTTPHeaderField:@"Content-Type"];
    [manager.requestSerializer setValue:source forHTTPHeaderField:@"Source"];
    [manager.requestSerializer setValue:sourceType forHTTPHeaderField:@"Sourcetype"];
    [manager.requestSerializer setValue:[self getDeviceIdentification] forHTTPHeaderField:@"deviceId"];
    if (ACCOUNT.token) {
        [manager.requestSerializer setValue:ACCOUNT.token forHTTPHeaderField:@"Token"];
    }
    
    if (ACCOUNT.clientKey) {
        [manager.requestSerializer setValue:ACCOUNT.clientKey forHTTPHeaderField:@"clientKey"];
    }
    
    NSString *userAgent = [manager.requestSerializer valueForHTTPHeaderField:@"user-agent"];
    NSString * appVersion = [[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleShortVersionString"];
    if (ACCOUNT.orgId.length) {
        [manager.requestSerializer setValue:[userAgent stringByAppendingString:[NSString stringWithFormat:@";orgid/%@;yunxuetang/%@",ACCOUNT.orgId, appVersion]] forHTTPHeaderField: @"user-agent"];
    } else {
        [manager.requestSerializer setValue:[userAgent stringByAppendingString:[NSString stringWithFormat:@";yunxuetang/%@",appVersion]] forHTTPHeaderField: @"user-agent"];
    }
    
    switch (methodType) {
        case RequestTypeGet:
        {
            //GET请求
            [manager GET:url parameters:params progress:^(NSProgress * _Nonnull downloadProgress) {
                
            } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
                // 状态栏隐藏菊花
                [UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
                if (success) {
                    success(task ,responseObject);
                }
            } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
                // 状态栏隐藏菊花
                [UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
                if (failure) {
                    failure(task, error);
                }
            }];
        }
            break;
        case RequestTypePost:
        {
            //POST请求
            [manager POST:url parameters:params progress:^(NSProgress * _Nonnull uploadProgress) {
                
            } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
                // 状态栏隐藏菊花
                [UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
                if (success) {
                    success(task ,responseObject);
                }
            } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
                // 状态栏隐藏菊花
                [UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
                if (failure) {
                    failure(task, error);
                }
            }];
        }
            break;
        case RequestTypeDelete:
        {
            //DELETE请求
            [manager DELETE:url parameters:params success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
                // 状态栏隐藏菊花
                [UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
                if (success) {
                    success(task, responseObject);
                }
            } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
                // 状态栏隐藏菊花
                [UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
                if (failure) {
                    failure(task, error);
                }
            }];
            
        }
            break;
        case RequestTypePut:
        {
            //PUT请求
            [manager PUT:url parameters:params success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
                // 状态栏隐藏菊花
                [UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
                if (success) {
                    
                    success(task, responseObject);
                }
            } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
                // 状态栏隐藏菊花
                [UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
                if (failure) {
                    failure(task, error);
                }
            }];
            
        }
            break;
        default:
            break;
    }
}

#pragma mark --系统相关
#pragma mark ----获取机构tabbar显示个数
- (void)appTabbarWithOrgId:(NSString *)orgId success:(void (^)(NSURLSessionDataTask *task,id response))success
                   failure:(void (^)(NSURLSessionDataTask * task, NSError *error))failure{
    NSString *url = [apiBaseURL stringByAppendingPathComponent:[NSString stringWithFormat:@"orgs/%@/toolBar",orgId]];
    
    [self requestWihtMethod:RequestTypeGet url:url
                              params:nil
                             success:success
                             failure:failure];
}

#pragma mark ----检查app版本号
- (void)checkAppVersionWithSuccess:(void (^)(NSURLSessionDataTask *task,id response))success
                         failure:(void (^)(NSURLSessionDataTask * task, NSError *error))failure{
    NSString * appVersion = [[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleShortVersionString"];
    NSString *url = [[apiBaseURL stringByAppendingPathComponent:@"system/appVersionSearch/2?version="] stringByAppendingString:appVersion];
    if ([self stringByLength:org_Code]) {
        url = [NSString stringWithFormat:@"%@&orgcode=%@",url,org_Code];
    } else {
        url = [NSString stringWithFormat:@"%@&orgcode=%@",url,ACCOUNT.orgCode];
    }
    
    BOOL flag = ![self stringByLength:org_Code];
    url = [NSString stringWithFormat:@"%@&isNew=%d", url,flag]; // isNew:通用包为True，定制包为False
    [self requestWihtMethod:RequestTypeGet url:url
                              params:nil
                             success:success
                             failure:failure];
}

#pragma mark ----crashlog 上传服务器
- (void)crashlogUploadServer:(NSDictionary *)crashInfo success:(void (^)(NSURLSessionDataTask *task,id response))success
                     failure:(void (^)(NSURLSessionDataTask * task, NSError *error))failure{
    NSString *url = [apiBaseURL stringByAppendingPathComponent:@"applog"];
    [self requestWihtMethod:RequestTypePost url:url
                     params:crashInfo
                    success:success
                    failure:failure];
}

#pragma mark --用户系统
#pragma mark ----用户信息
- (void)userInfoWithSuccess:(void (^)(NSURLSessionDataTask *task,id response))success
                    failure:(void (^)(NSURLSessionDataTask * task, NSError *error))failure{
    NSString *url = [apiBaseURL stringByAppendingPathComponent:@"userinfo"];
    [self requestWihtMethod:RequestTypeGet url:url
                              params:nil
                             success:success
                             failure:failure];
}

#pragma mark ----检查用户token有效性
- (void)mobileLogin:(NSDictionary *)userInfo success:(void (^)(NSURLSessionDataTask *task,id response))success
              failure:(void (^)(NSURLSessionDataTask * task, NSError *error))failure{
    NSString *url = [apiBaseURL stringByAppendingPathComponent:@"users/mobilelogin"];
    [self requestWihtMethod:RequestTypePost url:url
                              params:userInfo
                             success:success
                             failure:failure];
}

#pragma mark --检查用户token 是否过期(小乐才)
- (void)checkUserToken:(void (^)(NSURLSessionDataTask *task,id response))success
               failure:(void (^)(NSURLSessionDataTask * task, NSError *error))failure{
    NSString *url = [apiBaseURL stringByAppendingPathComponent:@"tokens/orguser"];
    [self requestWihtMethod:RequestTypeGet url:url
                              params:nil
                             success:success
                             failure:failure];
}


#pragma mark ----是否存在未读消息
- (void)isExistingUnreadMessageWithSuccess:(void (^)(NSURLSessionDataTask *task,id response))success
                    failure:(void (^)(NSURLSessionDataTask * task, NSError *error))failure{
    NSString *url = [apiBaseURL stringByAppendingPathComponent:@"users/mycount"];
    [self requestWihtMethod:RequestTypeGet url:url
                              params:nil
                             success:success
                             failure:failure];
}

#pragma mark ----用户是否能下载知识权限
- (void)knowledgeDownloadAuthoritySuccess:(void (^)(NSURLSessionDataTask *task,id response))success failure:(void (^)(NSURLSessionDataTask * task, NSError *error))failure{
    NSString *url = [apiBaseURL stringByAppendingPathComponent:[NSString stringWithFormat:@"orgs/%@/downvideo",ACCOUNT.orgId]];
    [self requestWihtMethod:RequestTypeGet url:url
                              params:nil
                             success:success
                             failure:failure];
}

#pragma mark --学习
#pragma mark --知识信息
- (void)knowledgeInfo:(NSDictionary *)knowledgeInfo success:(void (^)(NSURLSessionDataTask *task,id response))success
             failure:(void (^)(NSURLSessionDataTask * task, NSError *error))failure{
    NSString *url = [apiBaseURL stringByAppendingPathComponent:[NSString stringWithFormat:@"knowledge/%@",knowledgeInfo[@"knowledgeId"]]];
    [self requestWihtMethod:RequestTypePost url:url
                              params:knowledgeInfo
                             success:success
                             failure:failure];
}


#pragma mark --提交学分
- (void)submitCredit:(NSDictionary *)creditInfo success:(void (^)(NSURLSessionDataTask *task,id response))success
             failure:(void (^)(NSURLSessionDataTask * task, NSError *error))failure{
    NSString *url = [apiBaseURL stringByAppendingPathComponent:@"study"];
    [self requestWihtMethod:RequestTypePost url:url
                              params:creditInfo
                             success:success
                             failure:failure];
}

#pragma mark --批量学习进度提交
- (void)batchSubmitCredit:(NSMutableArray *)creditInfo success:(void (^)(NSURLSessionDataTask *task,id response))success
                  failure:(void (^)(NSURLSessionDataTask * task, NSError *error))failure{
    NSString *url = [apiBaseURL stringByAppendingPathComponent:@"study/batch"];
    [self requestWihtMethod:RequestTypePost url:url
                     params:creditInfo
                    success:success
                    failure:failure];
}

#pragma mark --播放器更新播放次数
- (void)playerUpdatePlayTimes:(NSString *)knowledgeId success:(void (^)(NSURLSessionDataTask *task,id response))success
                      failure:(void (^)(NSURLSessionDataTask * task, NSError *error))failure{
    NSString *url = [apiBaseURL stringByAppendingPathComponent:[NSString stringWithFormat:@"knowledges/%@/viewcount",knowledgeId]];
    [self requestWihtMethod:RequestTypePut url:url
                              params:nil
                             success:success
                             failure:failure];
}

#pragma mark --提交评论
- (void)submitComment:(NSDictionary *)commentInfo success:(void (^)(NSURLSessionDataTask *task,id response))success
              failure:(void (^)(NSURLSessionDataTask * task, NSError *error))failure{
    NSString *url = [apiBaseURL stringByAppendingPathComponent:@"comments"];
    [self requestWihtMethod:RequestTypePost url:url
                              params:commentInfo
                             success:success
                             failure:failure];
}

#pragma mark ----评论checkMark
- (void)commentCheckMark:(NSString *)knowledgeId success:(void (^)(NSURLSessionDataTask *task,id response))success
                 failure:(void (^)(NSURLSessionDataTask * task, NSError *error))failure{
    NSString *url = [apiBaseURL stringByAppendingPathComponent:[NSString stringWithFormat:@"comments/%@/checkMark",knowledgeId]];
    [self requestWihtMethod:RequestTypeGet url:url
                              params:nil
                             success:success
                             failure:failure];
}

#pragma mark ----收藏
- (void)collectKnowledge:(NSDictionary *)knowledgeInfo success:(void (^)(NSURLSessionDataTask *task,id response))success
                 failure:(void (^)(NSURLSessionDataTask * task, NSError *error))failure{
    NSString *url = [apiBaseURL stringByAppendingPathComponent:@"myCollection"];
    [self requestWihtMethod:RequestTypePost url:url
                              params:knowledgeInfo
                             success:success
                             failure:failure];
}

#pragma mark ----取消收藏
- (void)cancelCollectKnowledge:(NSString *)knowledgeId success:(void (^)(NSURLSessionDataTask *task,id response))success
                 failure:(void (^)(NSURLSessionDataTask * task, NSError *error))failure{
    NSString *url = [apiBaseURL stringByAppendingPathComponent:[NSString stringWithFormat:@"myCollection?knowledgeId=%@",knowledgeId]];
    [self requestWihtMethod:RequestTypeDelete url:url
                              params:nil
                             success:success
                             failure:failure];
}

#pragma mark --图片处理
#pragma mark --获取qiniu token
- (void)getQiniuTokenWithSuccess:(void (^)(NSURLSessionDataTask *task,id response))success
                         failure:(void (^)(NSURLSessionDataTask * task, NSError *error))failure{
    NSString *url = [apiBaseURL stringByAppendingPathComponent:@"qiniu/userPhoto/token?isPrivate=0"];
    [self requestWihtMethod:RequestTypeGet url:url
                              params:nil
                             success:success
                             failure:failure];
}

#pragma mark --上传用户头像
- (void)uploadUserPhoto:(NSString *)photoUrl success:(void (^)(NSURLSessionDataTask *task,id response))success
             failure:(void (^)(NSURLSessionDataTask * task, NSError *error))failure{
    NSDictionary *params = @{@"headPictureUrl":photoUrl};
    NSString *url = [apiBaseURL stringByAppendingPathComponent:[NSString stringWithFormat:@"users/%@/uploadPhoto",ACCOUNT.userId]];
    [self requestWihtMethod:RequestTypePut url:url
                              params:params
                             success:success
                             failure:failure];
}

#pragma mark --会议
#pragma mark ----获取用户相关信息
- (void)getMeetingAccountRelateWithSuccess:(void (^)(NSURLSessionDataTask *task,id response))success
                                   failure:(void (^)(NSURLSessionDataTask * task, NSError *error))failure{
    NSString *url = [meetingApiBaseURL stringByAppendingPathComponent:@"v1/currentuser"];
    [self requestWihtMethod:RequestTypeGet url:url
                              params:nil
                             success:success
                             failure:failure];
}
#pragma mark ----获取会汇账号信息
- (void)getMeetingAccountWithSuccess:(void (^)(NSURLSessionDataTask *task,id response))success
                             failure:(void (^)(NSURLSessionDataTask * task, NSError *error))failure{
    NSString *url = [meetingApiBaseURL stringByAppendingPathComponent:@"v1/mymeetingaccount"];
    [self requestWihtMethod:RequestTypeGet url:url
                              params:nil
                             success:success
                             failure:failure];
}

#pragma mark ----获取安排会议列表
- (void)meetingListWithSuccess:(void (^)(NSURLSessionDataTask *task,id response))success
                             failure:(void (^)(NSURLSessionDataTask * task, NSError *error))failure{
    NSString *url = [meetingApiBaseURL stringByAppendingPathComponent:@"v1/meetings"];
    [self requestWihtMethod:RequestTypeGet url:url
                              params:nil
                             success:success
                             failure:failure];
}

#pragma mark ----删除会议
- (void)meetingDeleteWithMeetingId:(NSString *)meetingId success:(void (^)(NSURLSessionDataTask *task,id response))success
                           failure:(void (^)(NSURLSessionDataTask * task, NSError *error))failure{
    NSString *url = [meetingApiBaseURL stringByAppendingPathComponent:[NSString stringWithFormat:@"%@/%@",@"v1/meetings",meetingId]];
    [self requestWihtMethod:RequestTypeDelete url:url
                              params:nil
                             success:success
                             failure:failure];
}

#pragma mark ----会议是否超过并发
- (void)meetingConcurrentBeyondWithMeetingId:(NSString *)meetingId success:(void (^)(NSURLSessionDataTask *task,id response))success
                           failure:(void (^)(NSURLSessionDataTask * task, NSError *error))failure{
    NSString *url = [meetingApiBaseURL stringByAppendingPathComponent:[NSString stringWithFormat:@"%@/%@/orginprogress",@"v1/meetings",meetingId]];
    [self requestWihtMethod:RequestTypeGet url:url
                              params:nil
                             success:success
                             failure:failure];
}

#pragma mark ----创建会议
- (void)meetingCreateWithSuccess:(void (^)(NSURLSessionDataTask *task,id response))success
                         failure:(void (^)(NSURLSessionDataTask * task, NSError *error))failure{
    NSString *url = [meetingApiBaseURL stringByAppendingPathComponent:@"v1/meetings"];
    NSMutableDictionary * params = [NSMutableDictionary dictionary];
    params[@"type"] = @1;
    params[@"option_jbh"] = @(true);
    [self requestWihtMethod:RequestTypePost url:url
                              params:params
                             success:success
                             failure:failure];
}

#pragma mark ----获取公共会议室列表
- (void)meetingPublicRoomList:(void (^)(NSURLSessionDataTask *task,id response))success failure:(void (^)(NSURLSessionDataTask * task, NSError *error))failure{
    NSString *url = [meetingApiBaseURL stringByAppendingString:@"v1/meetingrooms"];
    [self requestWihtMethod:RequestTypeGet url:url
                     params:nil
                    success:success
                    failure:failure];
}

#pragma mark ----搜索指定公共会议室列表
- (void)searchPublicRoomList:(NSDictionary *)searchInfo success:(void (^)(NSURLSessionDataTask *task,id response))success failure:(void (^)(NSURLSessionDataTask * task, NSError *error))failure{
    NSString *url = [meetingApiBaseURL stringByAppendingString:@"v1/publicmeetings/search"];
    [self requestWihtMethod:RequestTypePost url:url
                     params:searchInfo
                    success:success
                    failure:failure];
}

#pragma mark ----修改会议室名字
- (void)roomNameUpdate:(NSDictionary *)roomInfo success:(void (^)(NSURLSessionDataTask *task,id response))success failure:(void (^)(NSURLSessionDataTask * task, NSError *error))failure{
    NSString *url = [meetingApiBaseURL stringByAppendingString:[NSString stringWithFormat:@"v1/meetingrooms/%@",roomInfo[@"roomId"]]];
    [self requestWihtMethod:RequestTypePut url:url
                     params:roomInfo
                    success:success
                    failure:failure];
}


@end
